import 'package:flutter/material.dart';
import 'package:flutter_sqflite/DataModel.dart';
import 'package:flutter_sqflite/Database.dart';
import 'package:flutter_sqflite/components/DataCard.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController titleController = TextEditingController();
  TextEditingController subtitleController = TextEditingController();
  late DB db;
  List<DataModel> datas = [];
  bool fetching = true;
  int currentIndex = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    db = DB();
    getData();
  }

  void getData() async {
    datas = await db.getData();
    setState(() {
      fetching = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: fetching
          ? Center(child: CircularProgressIndicator())
          : ListView.builder(
              itemCount: datas.length,
              itemBuilder: (context, index) => DataCard(
                    data: datas[index],
                    edit: edit,
                    index: index,
                    delete: delete,
                  )),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          showMyDilogue();
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }

  void showMyDilogue() async {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            contentPadding: EdgeInsets.all(14),
            content: Container(
              height: 150,
              child: Column(children: [
                TextFormField(
                  controller: titleController,
                  decoration: InputDecoration(labelText: "title"),
                ),
                SizedBox(
                  height: 10,
                ),
                TextFormField(
                  controller: subtitleController,
                  decoration: InputDecoration(labelText: "subtitle"),
                )
              ]),
            ),
            actions: [
              TextButton(
                  onPressed: () {
                    DataModel dataLocal = DataModel(
                        title: titleController.text,
                        subtitle: subtitleController.text);

                    if (datas.isEmpty) {
                      dataLocal.id = 1;
                    } else if (datas.length == 1) {
                      dataLocal.id = 2;
                    } else {
                      dataLocal.id = datas[datas.length - 1].id! + 1;
                    }
                    db.insertData(dataLocal);
                    setState(() {
                      datas.add(dataLocal);
                    });
                    titleController.clear();
                    subtitleController.clear();
                    Navigator.pop(context);
                  },
                  child: Text("save"))
            ],
          );
        });
  }

  void showMyDilogueUpdate() async {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            contentPadding: EdgeInsets.all(14),
            content: Container(
              height: 150,
              child: Column(children: [
                TextFormField(
                  controller: titleController,
                  decoration: InputDecoration(labelText: "title"),
                ),
                SizedBox(
                  height: 10,
                ),
                TextFormField(
                  controller: subtitleController,
                  decoration: InputDecoration(labelText: "subtitle"),
                )
              ]),
            ),
            actions: [
              TextButton(
                  onPressed: () {
                    DataModel newData = datas[currentIndex];
                    newData.subtitle = subtitleController.text;
                    newData.title = titleController.text;
                    db.update(newData, newData.id!);
                    setState(() {});
                    Navigator.pop(context);
                  },
                  child: Text("update"))
            ],
          );
        });
  }

  void edit(index) {
    currentIndex = index;
    titleController.text = datas[index].title;
    subtitleController.text = datas[index].subtitle;
    showMyDilogueUpdate();
  }

  void delete(int index) {
    db.delete(datas[index].id!);
    setState(() {
      datas.removeAt(index);
    });
  }
}
